from app.extensions import db
from flask import request
from datetime import datetime
from app.models.model_mixin import BaseMixin


# article model
class Article(db.Model, BaseMixin):
    id = db.Column(db.Integer, primary_key=True)
    # 栏目ID 外键
    cid = db.Column(db.Integer, db.ForeignKey('category.id'))
    # 缩略图
    thumb = db.Column(db.String(255))
    # 标题
    title = db.Column(db.String(255))
    # 简要说明
    desc = db.Column(db.Text)
    # 正文
    content = db.Column(db.Text)
    # 文章状态 比如正常的文章，已删除的文章
    status = db.Column(db.Integer, default=9, index=True)
    # 排序
    sort = db.Column(db.Integer, default=0, index=True)
    # 是否是外链文章
    url = db.Column(db.String(255))
    # 点击数
    views = db.Column(db.Integer, default=0, index=True)
    # 创建时间
    created_at = db.Column(db.DateTime, default=datetime.now, index=True)
    # 更新时间 onupdate 更新会自动更新此时间
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)

    # 关联属性 分类
    category = db.relationship('Category', back_populates='articles')

    def to_dict(self, content=False):
        res_data = {
            'id': self.id,
            'cid': self.category.id,
            'thumb': self.thumb,
            'title': self.title,
            'status': self.status,
            'content': self.content,
            'url': self.url,
            'created_at': self.created_at,
        }
        if 'category' in request.args.get('expand', ''):
            res_data.update({
                'category': {
                    'id': self.category.id,
                    'title': self.category.title
                }
            })
        return res_data

    @staticmethod
    def to_collection_dict(query, page, per_page=10):
        resources = query.paginate(page, per_page, False)
        data = {
            'items': [item.to_dict() for item in resources.items],
            '_meta': {
                'page': page,
                'per_page': per_page,
                'total_pages': resources.pages,
                'total_items': resources.total
            }
        }
        return data
